$(function(){
    //图片即时显示
    function forthwith(){
        $('#inputCover').on('change',function(){
            let file= this.files[0];
            let src=URL.createObjectURL(file)
            $('#coverimg').prop('src',src)
        })
    }
    forthwith()

    //文章类别动态获取
    categoryClassify()
    function categoryClassify(){
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/list',
            headers:{
                Authorization :localStorage.getItem('token')
            },
            success(res){
                if(res.code==200){
                    // console.log(res)
                    let html=res.data.reduce((beforeHtml,value)=>beforeHtml+=`<option value="${value.id}">${value.name}</option>`,`<option value="">所有分类</option>`)
                    $('#category').html(html)
                }else{
                    console.log('失败',res)
                }
            }
        })
    }
    
    //layUI设置时间框
    time()
    function time(){
        const laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#articleDate' //指定元素
        });
    }
    //富文本编辑器
    editor()
    function editor(){
        tinymce.init({
            selector: '#articleContent',
            language:'zh_CN',//注意大小写
        });
    }

    //发表文章
    $('.btn-edit').on('click',function(){
        fn('已发布')
    })
    //文章草稿
    $('.btn-draft').on('click',function(){
        fn()
    })

    // 发表和草稿函数
    function fn(data=''){
        let formData=new FormData($('#form')[0])
        formData.append('content',tinyMCE.editors['articleContent'].getContent())
        formData.append('state',data)
        // formData.forEach((value,key)=>console.log('key',key,'value',value))
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/article/publish',
            data:formData,
            type:'post',
            headers:{
                Authorization :localStorage.getItem('token')
            },
            contentType:false,
            processData:false,
            success(res){
                if(res.code==200){
                    console.log(res.msg)
                    location.href='article_list.html'
                }
            }
        })
    }
})